layui.config({
    base : "/dhjdglxt/modules/util/"//自定义加载的模块
}).use(['form','layer','jquery','layedit','laydate','laypage','table','commUtil','element','treetable'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        laypage = layui.laypage,
        layedit = layui.layedit,
        laydate = layui.laydate,
        $ = layui.jquery;
    var table = layui.table;
    var commUtil = layui.commUtil;
    var element = layui.element;
    var treetable = layui.treetable;//很重要
    
    //机龄分析
    var datajlfx = [];
    //租赁性质分析
    var dataFjzlxz = [];
    var fjzlxzType = [];
    //飞机型号分析
    var fjxhfxlegend = [];
    var fjxhfxnf = [];
    var fjxhfxdata = [];
    //飞机引进分析
    var fjyjfxnf = [];
    var fjyjfxYjdata = [];
    var fjyjfxTcdata = [];
    
    var myChart = echarts.init(document.getElementById('eChartSpace'));
    var option1 = {};
    var option2 = {};
    function getEchartsdata(s_type,nf,starnf,endnf) {
    	if(s_type == 0){
    		//飞机引进分析
    		$.ajax({
    			type: "GET",
    			url: basePath + '/service/cxtj/fjyjfx',
    			async:false,
    		    dataType: "json",
    		    data:{'nf':nf,'starnf':starnf,'endnf':endnf},
    		    success: function(data){
    		    	if(data.length > 0){
    		    		for(var i=0;i<data.length;i++){
    		    			fjyjfxnf.push(data[i].nf);
    		    			fjyjfxYjdata.push(data[i].yj)
    		    			fjyjfxTcdata.push(data[i].tc)
    		    		}
    		    	}
    		    }
    		})
    		option1 = {
    		    tooltip: {
    		        trigger: 'axis',
    		        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
    		            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
    		        }
    		    },
    		    legend: {
    		    	data: ['退出', '引进']
    		    },
    		    grid: {
    		        left: '3%',
    		        right: '4%',
    		        bottom: '3%',
    		        containLabel: true
    		    },
    		    xAxis: [
    		        {
    		            type: 'value'
    		        }
    		    ],
    		    yAxis: [
    		        {
    		            type: 'category',
    		            axisTick: {
    		                show: false
    		            },
    		            data: fjyjfxnf
    		        }
    		    ],
    		    series: [
    		        {
    		            name: '引进',
    		            type: 'bar',
    		            stack: '总量',
    		            label: {
    		                show: true
    		            },
    		            data: fjyjfxYjdata
    		        },
    		        {
    		            name: '退出',
    		            type: 'bar',
    		            stack: '总量',
    		            label: {
    		                show: true,
    		                position: 'left'
    		            },
    		            data: fjyjfxTcdata
    		        }
    		    ]
    		};
    	} else if (s_type == 1) {
    		//机龄分析
    		$.ajax({
    			type: "GET",
    			url: basePath + '/service/cxtj/getJlfxList',
    			async:false,
    		    dataType: "json",
    		    data:{'nf':nf,'starnf':starnf,'endnf':endnf},
    		    success: function(data){
    		    	if(data.length > 0){
    		    		datajlfx.push(
    		    			{name: '0-5年', value: data[0].zerotofive},
    		    			{name: '5-10年', value: data[0].fivetoten},
    		    			{name: '10-15年', value: data[0].tentofifteen}
    		    		)
    		    	}
    		    }
    		})
    		option1 = {
				tooltip: {
			        trigger: 'item',
			        formatter: '{a} <br/>{b}: {c} ({d}%)'
			    },
			    legend: {
					type: 'scroll',
					orient: 'vertical',
					left: 10,
			        data: ['0-5年','5-10年','10-15年','15年以上']
			    },
			    series: [
			        {
			            name: '飞机机龄',
			            type: 'pie',
			            radius: ['50%', '70%'],
			            avoidLabelOverlap: false,
			            label: {
			                show: false,
			                position: 'center'
			            },
			            emphasis: {
			                label: {
			                    show: true,
			                    fontSize: '30',
			                    fontWeight: 'bold'
			                }
			            },
			            labelLine: {
			                show: false
			            },
			            data:datajlfx
			        }
			    ]
		   };
    		//飞机租赁性质分析
    		$.ajax({
    			type: "GET",
    			url: basePath + '/service/cxtj/getFjzlxzList',
    			async:false,
    		    dataType: "json",
    		    data:{'nf':nf,'starnf':starnf,'endnf':endnf},
    		    success: function(data){
    		    	if(data.length > 0){
    		    		for(var i=0;i<data.length;i++){
    		    			fjzlxzType.push(data[i].nature);
    		    			dataFjzlxz.push({
    		    				name:data[i].nature,
    		    				value:data[i].num
    		    			})
    		    		}
    		    	}
    		    }
    		})
    		option2 = {
    			tooltip: {
    		        trigger: 'item',
    		        formatter: '{a} <br/>{b}: {c} ({d}%)'
    		    },
    		    legend: {
    				type: 'scroll',
    				orient: 'vertical',
    				left: 10,
    		        data: fjzlxzType
    		    },
    		    series: [
    		        {
    		            name: '租赁性质',
    		            type: 'pie',
    		           /* avoidLabelOverlap: false,
    		            label: {
    		                show: false,
    		                position: 'center'
    		            },*/
    		            emphasis: {
    		                label: {
    		                    show: true,
    		                    fontSize: '30',
    		                    fontWeight: 'bold'
    		                }
    		            },
    		            labelLine: {
    		                show: false
    		            },
    		            data:dataFjzlxz
    		        }
    		    ]
    	   };
    	} else if (s_type == 2) {
    		//飞机型号分析
    		$.ajax({
    			type: "GET",
    			url: basePath + '/service/cxtj/fjxhfx',
    			async:false,
    		    dataType: "json",
    		    data:{'nf':nf,'starnf':starnf,'endnf':endnf},
    		    success: function(data){
    		    	if(data.length > 0){
    		    		for(var i=0;i<data.length;i++){
    		    			fjxhfxnf.push(data[i].nf);
    		    			if(i == 0) {
    		    				for(var key in data[i]){
    		    					if(key != "nf" && key != "allNum"){
    		    						fjxhfxlegend.push(key)
    		    					}
    		    				}
    		    			}
    		    		}
    		    		for(var i=0;i<fjxhfxlegend.length;i++){
    		    			var obj = {};
    		    			var datalist = [];
    		    			obj.name = fjxhfxlegend[i];
    		    			obj.type = 'bar';
    						obj.stack = '总量';
    						obj.label = {show: true,position: 'insideRight'};
    						for(var j=0;j<data.length;j++){
    							for(var key in data[j]){
    		    					if(key == fjxhfxlegend[i]){
    		    						datalist.push(data[j][key]);
    		    					}
    		    				}
    		    	        }
    						obj.data = datalist;
    						fjxhfxdata.push(obj);
    		    		}
    		    	}
    		    }
    		})
    		option1 = {
    		    tooltip: {
    		        trigger: 'axis',
    		        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
    		            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
    		        }
    		    },
    		    legend: {
    		        data: fjxhfxlegend
    		    },
    		    grid: {
    		        left: '3%',
    		        right: '4%',
    		        bottom: '3%',
    		        containLabel: true
    		    },
    		    xAxis: {
    		        type: 'value'
    		    },
    		    yAxis: {
    		        type: 'category',
    		        data: fjxhfxnf
    		    },
    		    series: fjxhfxdata
    		};
    	}
    }
    
    
    
    
    var urlList = ["/service/cxtj/getFjyjqlList","/service/cxtj/fjxxqk","/service/cxtj/lnjdxxb"];
    var headerList = [];
    var head0 = [[
    	{field:'nf',title: '年份',align:'center'}
    	,{field:'xh', title: '序号',align:'center'}
    	,{field:'jx', title: '机型',align:'center'}
    	,{field:'zch', title: '注册号',align:'center'}
    	,{field:'yjsj', title: '引进时间',align:'center'}
    	,{field:'bz', title: '备注', minWidth: 100,align:'center'} 
    ]]
    var head1 = [[
    	{type:'numbers',title: '序号',align:'center'}
    	,{field:'jx', title: '机型',align:'center'}
    	,{field:'zch', title: '注册号',align:'center'}
    	,{field:'ccsj', title: '出厂时间',align:'center'}
    	,{field:'yjsj', title: '进江苏时间',align:'center'}
    	,{field:'jl', title: '机龄（年）',align:'center'}
    	,{field:'xz', title: '性质',align:'center'}
    	,{field:'bz', title: '备注', minWidth: 100,align:'center'} 
    ]]
    var head2 = [];
    $.ajax({
    	url: basePath +"/service/cxtj/jxlist",
    	type: "GET",
    	async:false,
        dataType: "json",
    	success:function(data) {
    		var zzhead = [];
    		zzhead.push({field:'nf',title: '年份',align:'center',minWidth: 100});
    		if(data.length>0){
    			for(var i = 0 ; i<data.length; i++ ){
    				zzhead.push({field:data[i].airModel,title: data[i].airModel,align:'center',minWidth: 80});
    			}
    			zzhead.push({field:'allNum',title: '年末在用飞机架数',align:'center',minWidth: 150});
    		}
    		head2.push(zzhead);
    	}
    })
    headerList[0] = head0;
    headerList[1] = head1;
    headerList[2] = head2;
    
    laydate.render({
	    elem: '#s_starnf',
	    trigger: 'click',
	    type:'year'
	});
    laydate.render({
	    elem: '#s_endnf',
	    trigger: 'click',
	    type:'year'
	});
    
    
    table.render({
        elem: '#myTable'
        ,cols: headerList[0]
    	,page: false
    	,limit: Number.MAX_VALUE
        ,url: basePath +urlList[0]
        , done: function (res,curr,count) {
        	merge(res,["nf"],[0]);
            this.cols = []
            getEchartsdata(0,5,'','');
            myChart.setOption(option1);
        }
    });
    
    
    
    form.on('select(s_nf)', function(data){
    	if(data.value == '4'){
    		$("#qujian").show();
    	} else {
    		$("#qujian").hide();
    		var s_starnf = $("#s_starnf").val("");
        	var s_endnf = $("#s_endnf").val("");
    	}
	});   
    

    $(".onQuery").click(function(){
        onQuery();
    })

    
    //查询
    function onQuery(){
    	//机龄分析
        datajlfx = [];
        //租赁性质分析
        dataFjzlxz = [];
        fjzlxzType = [];
        //飞机型号分析
        fjxhfxlegend = [];
        fjxhfxnf = [];
        fjxhfxdata = [];
        //飞机引进分析
        fjyjfxnf = [];
        fjyjfxYjdata = [];
        fjyjfxTcdata = [];
    	
    	
    	option1 = {};
    	var s_type = $("#s_type").val();
    	var s_nf = $("#s_nf").val();
    	var s_starnf = $("#s_starnf").val();
    	var s_endnf = $("#s_endnf").val();
    	if(s_type == 1){
    		$("#myTable").before("<table class=\"layui-hide\" id=\"beforeTable\"></table>")
    		form.render();
    		table.render({
                elem: '#beforeTable'
                ,cols: [[
                	{field:'xh', title: '机型',align:'center'}
                	,{field:'num', title: '数量',align:'center'}
                	,{field:'hj', title: '合计数量',align:'center'}
                	,{field:'pjjl', title: '平均机龄',align:'center'}
                	,{field:'gxrq', title: '更新日期',align:'center'}
                ]]
            	,page: false
            	,limit: Number.MAX_VALUE
                ,url: basePath +'/service/cxtj/fjxxqkhj'
    	    	,where: {
    	        	s_type: s_type,
    	        	s_nf: s_nf,
    	        	s_starnf: s_starnf,
    	        	s_endnf: s_endnf
    	        }
                , done: function (res,curr,count) {
                	merge(res,["hj","pjjl","gxrq"],[2,3,4]);
                }
            });
    	} else {
    		$("#beforeTable").remove();
    		$("div[lay-id$='beforeTable']").remove();
    		form.render();
    	}
    	
        //执行重载
        table.reload('myTable', {
        	cols: headerList[s_type],
        	url: basePath +urlList[s_type],
        	limit: Number.MAX_VALUE,
        	page: false,
            where: {
            	s_type: s_type,
            	s_nf: s_nf,
            	s_starnf: s_starnf,
            	s_endnf: s_endnf
            }, done: function (res,curr,count) {
            	this.cols = [];
            	if(s_type == 0){
            		merge(res,["nf"],[0]);
            	} 
            	myChart.clear();
            	getEchartsdata(s_type,s_nf,s_starnf,s_endnf);
            	if(s_type == 1){
            		$("#eChartSpace").css({"width":"45%","float":"left"})
        			myChart.resize();
            		if($("#eChartSpaceTwo").length > 0){
            			$("#eChartSpaceTwo").show();
            		} else {
            			$("#eChartSpace").after("<div id='eChartSpaceTwo' style='width:45%;height:300px;float:left'></div>")
            		}
            		form.render();	
            		var myChart1 = echarts.init(document.getElementById('eChartSpaceTwo'));
            		myChart1.setOption(option2)
            	} else {
            		$("#eChartSpaceTwo").hide();
            		$("#eChartSpace").css({"width":"90%"})
            		myChart.resize();
            	}
            	myChart.setOption(option1);
            }
        });
    }
    
    
    function merge(res,colName,columsIndex) {
    	 
        var data = res.data;
        var mergeIndex = 0;//定位需要添加合并属性的行数
        var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
        var columsName = colName;//需要合并的列名称  [] 数组
        var columsIndex = columsIndex;//需要合并的列索引值 [] 数组

        for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
            var trArr = $(".layui-table-body>.layui-table").find("tr");//所有行
            for (var i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
                var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
                var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列

                if (data[i][columsName[k]] === data[i-1][columsName[k]]) { //后一行的值与前一行的值做比较，相同就需要合并
                    mark += 1;
                    tdPreArr.each(function () {//相同列的第一列增加rowspan属性
                        $(this).attr("rowspan", mark);
                    });
                    tdCurArr.each(function () {//当前行隐藏
                        $(this).css("display", "none");
                    });
                }else {
                    mergeIndex = i;
                    mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                }
            }
            mergeIndex = 0;
            mark = 1;
        }
    }
    $(".ondc").click(function(){
    	var s_type = $("#s_type").val();
    	var s_nf = $("#s_nf").val();
    	var s_starnf = $("#s_starnf").val();
    	var s_endnf = $("#s_endnf").val();
    	window.open(basePath+'/service/cxtj/down?s_type='+s_type+'&s_nf='+s_nf+'&s_starnf='+s_starnf+'&s_endnf='+s_endnf, '_blank').location;
    })
    
    
})